package com.example.lib_common.view.view

import android.app.Activity.RESULT_OK
import android.content.Intent
import android.os.Bundle
import androidx.activity.result.contract.ActivityResultContracts
import androidx.databinding.ViewDataBinding
import com.example.lib_base.view.BaseFragment
import com.example.lib_common.view.event.CustomEvent
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

abstract class BaseMvvmFragment<VDB:ViewDataBinding>:BaseFragment<VDB>() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //获取数据
        loadData()
        //订阅数据
        observeDataChanged()
        //EventBus事件总线
        EventBus.getDefault().register(this)
    }

    //接收事件
    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun onReceiveEvent(event: CustomEvent?) {
        if (event!=null && event.target==this.javaClass.simpleName){
            //处理业务
            handEvent(event)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
    private val resultLauncher=registerForActivityResult(ActivityResultContracts.StartActivityForResult()){ result ->
        if(result.resultCode== RESULT_OK){
            result.data?.run {
                handActivityResult(this)
            }
        }
    }

    protected open fun handActivityResult(it: Intent){

    }
    protected open fun startNextActivityForResult(intent:Intent){
        resultLauncher.launch(intent)
    }


    protected open fun startNextActivity(intent: Intent?){
        intent?.run {
            startActivity(this)
        }
    }

    protected open fun startNextActivityForResult(intent:Intent?,requestCode:Int){
        intent?.run {
            startActivityForResult(this,requestCode)
        }
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        receiverNextForResult(requestCode, resultCode, data)

    }

    protected open fun receiverNextForResult(requestCode:Int,resultCode:Int,data:Intent?){

    }

    protected open fun observeDataChanged() {}

    protected open fun loadData() {}
    protected open fun handEvent(event: CustomEvent){}
}